<template>
	<el-card>
		<el-form
			label-width="120px"
			:model="skuInfo"
			:rules="skuFormRules"
			ref="skuFormRef"
		>
			<el-form-item label="SPU名称">
				<span>{{ currentSpuInfo.spuName }}</span>
			</el-form-item>
			<el-form-item label="SKU名称" prop="skuName">
				<el-input v-model="skuInfo.skuName" placeholder="SKU名称"></el-input>
			</el-form-item>
			<el-form-item label="价格(元)" prop="price">
				<el-input
					v-model="skuInfo.price"
					type="number"
					:min="0"
					:max="100"
				></el-input>
			</el-form-item>
			<el-form-item label="重量(千克)" prop="weight">
				<el-input
					v-model="skuInfo.weight"
					type="number"
					:min="0"
					:max="100"
				></el-input>
			</el-form-item>
			<el-form-item label="规格描述" prop="skuDesc">
				<el-input
					type="textarea"
					placeholder="请输入SKU描述"
					v-model="skuInfo.skuDesc"
					rows="4"
				></el-input>
			</el-form-item>

			<el-form-item label="平台属性" prop="skuAttrValueList">
				<el-row :gutter="10">
					<el-col
						v-for="(attr, index) in attrList"
						:key="attr.id"
						:xs="24"
						:sm="12"
						:md="8"
						:lg="8"
						:xl="6"
					>
						<el-form-item style="margin-bottom: 10px" :label="attr.attrName">
							<el-select
								v-model="skuInfo.skuAttrValueList[index]"
								placeholder="请选择"
								@change="toClearAttrValueRules"
							>
								<el-option
									v-for="attrValue in attr.attrValueList"
									:key="attrValue.id"
									:label="attrValue.valueName"
									:value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form-item>

			<el-form-item label="销售属性" prop="skuSaleAttrValueList">
				<el-row :gutter="10">
					<el-col
						v-for="(saleAttr, index) in spuSaleAttrList"
						:key="saleAttr.id"
						:xs="24"
						:sm="12"
						:md="12"
						:lg="8"
						:xl="8"
					>
						<el-form-item :label="saleAttr.saleAttrName">
							<el-select
								v-model="skuInfo.skuSaleAttrValueList[index]"
								placeholder="请选择"
								@change="toClearSaleAttrRules"
							>
								<el-option
									v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
									:label="saleAttrValue.saleAttrValueName"
									:value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
									:key="saleAttrValue.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form-item>
			<el-form-item label="图片列表" prop="skuImageList">
				<el-table
					border
					:data="spuImageList"
					@selection-change="handleSelectionChange"
				>
					<el-table-column
						type="selection"
						align="center"
						width="80"
					></el-table-column>
					<el-table-column label="图片">
						<template v-slot="{ row }">
							<el-image
								style="width: 100px; height: 100px"
								:src="row.imgUrl"
								fit="fill"
							/>
						</template>
					</el-table-column>
					<el-table-column label="名称" prop="imgName"></el-table-column>
					<el-table-column label="操作">
						<template v-slot="{ row }">
							<el-button
								type="primary"
								v-if="row.isDefault === '0'"
								@click="toSetDefaultImg(row)"
							>
								设置默认图片
							</el-button>
							<el-button type="success" v-else disabled>默认图片</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
			<el-button
				type="primary"
				style="margin-left: 120px"
				@click="submitSkuForm(skuFormRef)"
				>保存</el-button
			>
			<el-button @click="emits('setShowStatus', ShowStatus.SPU_LIST)"
				>取消</el-button
			>
		</el-form>
	</el-card>
</template>

<script lang="ts">
export default {
	name: 'SkuForm',
}
</script>

<script lang="ts" setup>
import { onMounted, ref, reactive } from 'vue'
import { reqGetAttrListData } from '@/api/product/attr'
import {
	reqGetSpuImageListData,
	reqGetSpuSaleAttrListData,
} from '@/api/product/spu'
import { useCategoryListStore } from '@/stores/categoryList'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { reqSaveSkuInfo } from '@/api/product/sku'
import { ShowStatus } from '../types'

const props = defineProps(['currentSpuInfo'])
const emits = defineEmits(['setShowStatus'])
const categoryStore = useCategoryListStore()
const spuImageList = ref([])
const spuSaleAttrList = ref([])
const attrList = ref([])
const skuFormRef = ref<FormInstance>()
const skuInfo = reactive({
	skuName: '',
	spuId: -1,
	tmId: 0,
	weight: 1,
	skuDefaultImg: '',
	skuDesc: '',
	category3Id: 0,
	price: 1,
	skuAttrValueList: [],
	skuImageList: [],
	skuSaleAttrValueList: [],
})
// 自定义校验规则
const skuAttrValueListRule = (rule: any, value: any, callback: any) => {
	if (!value.length) {
		callback('平台属性至少选择一个')
		return
	}
	callback()
}

const skuSaleAttrValueListRule = (rule: any, value: any, callback: any) => {
	if (!value.length) {
		return callback('请至少选择一个销售属性')
	}
	callback()
}

// 验证图片
const skuImageListRule = (rule: any, value: any, callback: any) => {
	if (value.length < 3) {
		return callback('请至少选择三张图片')
	}
	callback()
}
// 书写校验规则
const skuFormRules = reactive<FormRules>({
	skuName: [
		{ required: true, message: '请填写SKU名称', trigger: 'blur' },
		{ min: 2, max: 10, message: '长度应该在2~10之间', trigger: 'blur' },
	],
	price: [
		{
			required: true,
			message: '请设置一个价格',
			trigger: 'change',
		},
	],
	weight: [
		{
			required: true,
			message: '请添加一个重量',
			trigger: 'change',
		},
	],
	skuDesc: [{ required: true, message: '请输入SKU描述', trigger: 'blur' }],
	skuImageList: [
		{ required: true, validator: skuImageListRule, trigger: 'change' },
	],
	skuAttrValueList: [
		{ required: true, validator: skuAttrValueListRule, trigger: 'change' },
	],
	skuSaleAttrValueList: [
		{ required: true, validator: skuSaleAttrValueListRule, trigger: 'change' },
	],
})
// 挂载完毕请求三种数据
onMounted(async () => {
	try {
		const { id: spuId } = props.currentSpuInfo
		const { category1Id, category2Id, category3Id } = categoryStore
		const [resSpuImageList, resSpuSaleAttrList, resAttrList] =
			await Promise.allSettled([
				reqGetSpuImageListData(spuId),
				reqGetSpuSaleAttrListData(spuId),
				reqGetAttrListData({ category1Id, category2Id, category3Id }),
			])

		if (resSpuImageList.status === 'fulfilled') {
			spuImageList.value = resSpuImageList.value.map((item) => {
				return {
					...item,
					isDefault: '0',
				}
			})
		}
		if (resSpuSaleAttrList.status === 'fulfilled') {
			spuSaleAttrList.value = resSpuSaleAttrList.value
		}
		if (resAttrList.status === 'fulfilled') {
			attrList.value = resAttrList.value
		}
	} catch (error) {
		console.log('errr', error)
	}
})
// 设置默认图片
const toSetDefaultImg = (row) => {
	spuImageList.value.forEach((item) => {
		item.isDefault = '0'
	})
	row.isDefault = '1'
	skuInfo.skuDefaultImg = row.imgUrl
}
// 清空平台属性校验
const toClearAttrValueRules = () => {
	skuFormRef.value?.clearValidate(['skuAttrValueList'])
}
// 清空销售属性的校验
const toClearSaleAttrRules = () => {
	skuFormRef.value?.clearValidate(['skuSaleAttrValueList'])
}
// 收集选择的图片
const handleSelectionChange = (val) => {
	if (val.length >= 3) {
		skuFormRef.value?.clearValidate(['skuImageList'])
	}
	// 收集图片
	skuInfo.skuImageList = val
}
// 添加skuInfo
const submitSkuForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate(async (valid) => {
		if (valid) {
			skuInfo.skuAttrValueList = skuInfo.skuAttrValueList
				.filter(Boolean)
				.map((item) => {
					const [attrId, attrName, valueId, valueName] = item.split(':')
					return {
						attrId,
						attrName,
						valueId,
						valueName,
					}
				})
			skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList
				.filter(Boolean)
				.map((item) => {
					const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] =
						item.split(':')
					return {
						saleAttrId,
						saleAttrName,
						saleAttrValueId,
						saleAttrValueName,
					}
				})
			if (!skuInfo.skuImageList.find((item) => item.isDefault === '1')) {
				ElMessage.warning('请在图片列表中选择一张默认图片')
				return
			}
			skuInfo.category3Id = categoryStore.category3Id
			skuInfo.spuId = props.currentSpuInfo.id
			skuInfo.tmId = props.currentSpuInfo.tmId

			await reqSaveSkuInfo(skuInfo)
			ElMessage.success('添加skuInfo成功')
			emits('setShowStatus', ShowStatus.SPU_LIST)
		} else {
			console.log('error submit')
			return false
		}
	})
}
</script>

<style scoped></style>
